package com.aaa.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.aaa.entity.Result;
import com.aaa.util.ThreadLocalUtil;
import com.aaa.util.TokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.lang.NonNull;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;

@Component
public class JwtFilter extends OncePerRequestFilter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain)
            throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        // 跳过不需要验证的路径
        if (requestURI.equals("/api/users/login") ||
                requestURI.startsWith("/swagger-ui") ||
                requestURI.startsWith("/swagger-resources") ||
                requestURI.startsWith("/v2/api-docs") ||
                requestURI.startsWith("/webjars")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 从请求头中提取 JWT
        String token = TokenUtil.extractToken(request);
        
        try {
            // 解析token获取claims
            Map<String, Object> claims = TokenUtil.parseToken(token);
            
            // 检查claims是否有效
            if (claims == null || !claims.containsKey("id")) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                Result<?> errorResult = Result.unauthorized("Token无效或未提供有效的认证Token");
                response.getWriter().write(objectMapper.writeValueAsString(errorResult));
                return;
            }

            // 将解析出的用户信息存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            // 设置Spring Security的认证信息
            UsernamePasswordAuthenticationToken authentication = 
                new UsernamePasswordAuthenticationToken(
                    claims.get("id"), 
                    null, 
                    Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                );
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 继续过滤器链
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            Result<?> errorResult = Result.unauthorized("Token解析失败");
            response.getWriter().write(objectMapper.writeValueAsString(errorResult));
        } finally {
            // 请求结束后清理ThreadLocal和SecurityContext
            ThreadLocalUtil.remove();
            SecurityContextHolder.clearContext();
        }
    }
}